import { Form, Table } from 'antd';
import Cls from 'classnames';
import { getMaterialTableConfig, handListMoment } from '../mconfig';
import { useContext, useEffect, useMemo, useState } from 'react';
import { ContractManageAPI } from '../common/type';
import { getKeyRouter } from '@/utils';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import _ from 'lodash';
import CreateExcel from 'js-export-excel';
import { OpenMaterialImportModal } from './OpenMaterialImportModal';

export const UpdateMaterialTableView: React.FC<ContractManageAPI.IUpdateMaterialTableView> = ({ formName, loadMapInfo, setOpenMaterialModal }) => {
  // /** 获取上下文 */
  const { pageType, contractDetailInfo, contractForm, contarctJsonList, contractDispatch } = useContext(ConractControllerContext);

  /** 保存供货数据 */
  const [materialDataSource, setMaterialDataSource] = useState<Record<string, any>[]>(formName?.getFieldValue('detailList'));

  /** 是否打开导入弹框 */
  const [materialImportModal, setMaterialImportModal] = useState<boolean>(false);

  useEffect(() => {
    if (pageType == 'modify') {
      if (materialDataSource?.length > 0) {
        formName?.setFieldsValue({
          detailList: materialDataSource?.length > 0 ? materialDataSource : [],
        });
      }
    } else {
      formName?.setFieldsValue({
        detailList: materialDataSource?.length > 0 ? materialDataSource : [],
      });
    }
  }, [materialDataSource?.length]);

  // /** 详情初始化 */
  useEffect(() => {
    if (contractDetailInfo?.id) {
      const detailList: Record<string, any>[] = handListMoment(contractDetailInfo?.detailList, ['deliveryTime'], false);
      setMaterialDataSource(detailList);
    }
  }, [contractDetailInfo?.detailList?.length]);

  /** 添加供货 */
  const addMaterialCallback = () => {
    const addItemObj: Record<string, any> = {
      key: `detailList-${getKeyRouter()}`,
      modifyFlag: 0,
    };
    let changeList: Record<string, any>[] = contarctJsonList?.['detailList']?.length > 0 ? contarctJsonList?.['detailList'] : [];
    changeList?.push(addItemObj);
    contractDispatch({
      type: IContractsActionEnum.CONTRACT_JSONLIST,
      payload: {
        ...contarctJsonList,
        detailList: changeList,
      },
    });

    const formDetailList: Record<string, any>[] = formName?.getFieldValue('detailList');
    const materFormValue: Record<string, any>[] = formDetailList && formDetailList?.length > 0 ? formDetailList : [];
    let newMaterial: Record<string, any>[] = [...materFormValue];
    newMaterial?.push(addItemObj);
    setMaterialDataSource(newMaterial);
  };

  /** 删除物料 */
  const delMaterialCallback = (resObj: Record<string, any>) => {
    let newChangeList: Record<string, any>[] = [];
    let changeList: Record<string, any>[] = contarctJsonList?.['detailList']?.length > 0 ? contarctJsonList?.['detailList'] : [];
    if (resObj && resObj?.id) {
      const delObj: Record<string, any> = {
        ...resObj,
        modifyFlag: '2',
      };
      newChangeList = changeList?.filter((item: any) => item?.id != delObj?.id);
      newChangeList?.push(delObj);
    } else if (resObj && resObj?.key) {
      newChangeList = changeList?.filter((item: any) => item?.key != resObj?.key);
    }
    contractDispatch({
      type: IContractsActionEnum.CONTRACT_JSONLIST,
      payload: {
        ...contarctJsonList,
        detailList: newChangeList,
      },
    });

    const newDetailList: Record<string, any>[] = contractForm?.getFieldValue('detailList');
    const newMaterial: Record<string, any>[] = newDetailList?.filter((item: any) => item?.id != resObj?.id || item?.key != resObj?.key);
    setMaterialDataSource(newMaterial);
    formName?.setFieldsValue({
      detailList: newMaterial?.length > 0 ? newMaterial : [],
    });
  };

  /**物料导入 */
  const materialImport = () => {
    setMaterialImportModal(true);
  };

  /** 物料导出 */
  const materialExport = () => {
    const dataInfoList: Record<string, any>[] = contractForm.getFieldValue('detailList')?.length > 0 ? contractForm.getFieldValue('detailList') : [];
    let option: any = {};
    option.fileName = `供货服务清单`;
    option.datas = [
      {
        sheetData: dataInfoList,
        sheetName: '供货服务清单',
        sheetFilter: [
          'materialID',
          'materialName',
          'specInfo',
          'expectNum',
          'unitBusinessName',
          'taxRate',
          'priceInTax',
          'sumInTax',
          'deliveryTime',
          'deliveryAddress',
          'deliveryStyle',
        ],
        sheetHeader: ['编号', '分项名称', '规格要求（参数）', '数量', '单位', '税率', '含税单价（元）', '合价（元）', '交付时间', '交付地点', '交付方式'],
      },
    ];
    let toExcel = new CreateExcel(option);
    toExcel?.saveExcel();
  };

  /** 表格行配置 */
  const columnsMemo = useMemo(() => {
    return getMaterialTableConfig(
      addMaterialCallback,
      delMaterialCallback,
      formName,
      loadMapInfo,
      pageType,
      setOpenMaterialModal,
      materialImport,
      materialExport,
    );
  }, [materialDataSource, loadMapInfo, contarctJsonList]);

  return (
    <>
      <div className={Cls('list-table', 'descriptionsType-tableSty', 'descriptionsType-tableFormSty')}>
        <Form.Item name="detailList" valuePropName="dataSource">
          <Table
            columns={columnsMemo}
            bordered
            size="small"
            dataSource={materialDataSource}
            rowKey={(res) => (res?.id ? res?.id : res?.key)}
            scroll={{ x: 1200, y: '' }}
            pagination={false}
          />
        </Form.Item>
      </div>

      {materialImportModal && (
        <OpenMaterialImportModal
          onClose={() => {
            setMaterialImportModal(false);
          }}
          setMaterialDataSource={setMaterialDataSource}
        />
      )}
    </>
  );
};
